package middleware

import (
	"bytes"
	"fmt"
	"runtime"

	"github.com/gin-gonic/gin"
)

var (
	dunno     = []byte("???")
	centorDot = []byte(".")
	dot       = []byte(".")
	slash     = []byte("/")
)

func function(pc uintptr) []byte {
	fn := runtime.FuncForPC(pc)
	if fn == nil {
		return dunno
	}

	name := []byte(fn.Name())
	if lastslash := bytes.LastIndex(name, slash); lastslash >= 0 {
		name = name[lastslash+1:]
	}
	if period := bytes.Index(name, dot); period >= 0 {
		name = name[period+1:]
	}
	name = bytes.Replace(name, centorDot, dot, -1)
	return name
}

func stack(skip int) []string {
	var buf []string
	for i := skip; ; i++ {
		pc, file, line, ok := runtime.Caller(i)
		if !ok {
			break
		}
		s := fmt.Sprintf("%s:%d:in '%s'\n", file, line, function(pc))
		buf = append(buf, s)
	}
	return buf
}

func BacktraceM() gin.HandlerFunc {
	return backtrace
}

func backtrace(c *gin.Context) {
	defer func() {
		if err := recover(); err != nil {
			c.Set("panicError", map[string]interface{}{
				"reason":    err,
				"backtrace": stack(4),
			})
			c.AbortWithStatus(500)
		}
	}()
	c.Next()
}
